from flask import Flask, request, render_template, send_from_directory
import os

app = Flask(__name__)

# 设置一个上传文件的 HTML 表单页面
@app.route('/')
def upload_file():
    return render_template('upload.html')

# 处理上传的文件
@app.route('/upload', methods=['POST'])
def uploaded_file():
    if 'file' not in request.files:
        return 'No file part'

    files = request.files.getlist('file')  # 获取上传的多个文件
    if not files:
        return 'No selected file'

    upload_folder = 'D:/myupdata/'  # 指定保存文件的目录
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)

    for file in files:
        if file.filename == '':
            return 'No selected file'

        file.save(os.path.join(upload_folder, file.filename))  # 保存文件到指定目录

    return 'Files uploaded successfully'


# 路由用于展示文件列表并提供下载链接
@app.route('/files')
def file_list():
    upload_folder = 'D:/myupdata/'  # 指定文件目录
    files = os.listdir(upload_folder)  # 获取目录下的文件列表
    return render_template('file_list.html', files=files)

# 路由用于提供文件下载
@app.route('/download/<path:filename>')
def download_file(filename):
    upload_folder = 'D:/myupdata/'  # 指定文件目录
    return send_from_directory(upload_folder, filename, as_attachment=True)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)
